package userInterface.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import logic.DatabaseBroker;

public class MainScreen {
	private DatabaseBroker db = null;
	
	private JFrame MainFrame;
	private JTextField BinaryFileTF;
	private JTextField CsvFileTF;
	private JTextField CtlFileTF;
	private JTextField AliasTF;
	private JButton DoMonthEndButton;
	private JButton CheckPayrollButton;
	private JButton CreateCSVButton;
	private JButton ExportButton;
	
	private String username = "";
	private String password = "";
	private JLabel lblExportFileName;
	private JTextField ExportFileTF;
	/**
	 * Create the application.
	 */
	public MainScreen() {
		db = DatabaseBroker.getDatabaseBroker();
		initialize();
		this.MainFrame.setVisible(true);
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		MainFrame = new JFrame();
		MainFrame.setTitle("Payroll Processing");
		MainFrame.setBounds(100, 100, 554, 311);
		MainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		MainFrame.getContentPane().setLayout(null);
		
		CheckPayrollButton = new JButton("Check Payroll");
		CheckPayrollButton.setBounds(166, 11, 362, 23);
		CheckPayrollButton.addActionListener(new ButtonListener());
		MainFrame.getContentPane().add(CheckPayrollButton);
		
		CreateCSVButton = new JButton("Create CSV");
		CreateCSVButton.setBounds(166, 36, 362, 23);
		CreateCSVButton.setEnabled(false);
		CreateCSVButton.addActionListener(new ButtonListener());
		MainFrame.getContentPane().add(CreateCSVButton);
				
		DoMonthEndButton = new JButton("Do Month End");
		DoMonthEndButton.setBounds(166, 152, 362, 23);
		DoMonthEndButton.setEnabled(false);
		DoMonthEndButton.addActionListener(new ButtonListener());
		MainFrame.getContentPane().add(DoMonthEndButton);
		
		ExportButton = new JButton("Export");
		ExportButton.setBounds(166, 186, 362, 23);
		ExportButton.setEnabled(false);
		ExportButton.addActionListener(new ButtonListener());
		MainFrame.getContentPane().add(ExportButton);
		
		JLabel lblLoadData = new JLabel("Step 1: Load Data: ");
		lblLoadData.setBounds(10, 15, 124, 14);
		MainFrame.getContentPane().add(lblLoadData);
		
		JLabel lblExportAsCsv = new JLabel("Step 2: Export as CSV: ");
		lblExportAsCsv.setBounds(10, 40, 124, 14);
		MainFrame.getContentPane().add(lblExportAsCsv);
		
		JLabel lblCSVFILE = new JLabel("CSV FILE: ");
		lblCSVFILE.setBounds(10, 96, 89, 14);
		MainFrame.getContentPane().add(lblCSVFILE);
		
		JLabel lblBINARYFILE = new JLabel("BINARY FILE: ");
		lblBINARYFILE.setBounds(10, 71, 89, 14);
		MainFrame.getContentPane().add(lblBINARYFILE);
		
		JLabel lblMonthEnd = new JLabel("Step 3: Perform Month End: ");
		lblMonthEnd.setBounds(10, 156, 157, 14);
		MainFrame.getContentPane().add(lblMonthEnd);
		
		JLabel lblExportData = new JLabel("Step 4: Export Data: ");
		lblExportData.setBounds(10, 190, 124, 14);
		MainFrame.getContentPane().add(lblExportData);
		
		BinaryFileTF = new JTextField();
		BinaryFileTF.setBounds(109, 65, 419, 20);
		MainFrame.getContentPane().add(BinaryFileTF);
		BinaryFileTF.setColumns(10);
		BinaryFileTF.setText("c:\\cprg300\\payroll.bin");
		
		CsvFileTF = new JTextField();
		CsvFileTF.setBounds(109, 93, 419, 20);
		MainFrame.getContentPane().add(CsvFileTF);
		CsvFileTF.setColumns(10);
		CsvFileTF.setText("c:\\cprg300\\payrollCSV.txt");
		
		CtlFileTF = new JTextField();
		CtlFileTF.setBounds(109, 121, 419, 20);
		MainFrame.getContentPane().add(CtlFileTF);
		CtlFileTF.setColumns(10);
		CtlFileTF.setText("c:\\cprg300\\control.ctl");
		
		AliasTF = new JTextField();
		AliasTF.setBounds(109, 220, 419, 20);
		MainFrame.getContentPane().add(AliasTF);
		AliasTF.setColumns(10);
		AliasTF.setText("OutputFile");
		
		ExportFileTF = new JTextField();
		ExportFileTF.setText("output.csv");
		ExportFileTF.setBounds(131, 248, 397, 20);
		MainFrame.getContentPane().add(ExportFileTF);
		ExportFileTF.setColumns(10);
		
		JLabel lblCtlFile = new JLabel("CTL FILE:");
		lblCtlFile.setBounds(10, 124, 94, 14);
		MainFrame.getContentPane().add(lblCtlFile);
		
		JLabel lblAlias = new JLabel("ALIAS FILE:");
		lblAlias.setBounds(10, 223, 94, 14);
		MainFrame.getContentPane().add(lblAlias);
		
		lblExportFileName = new JLabel("EXPORT FILE NAME: ");
		lblExportFileName.setBounds(10, 251, 111, 14);
		MainFrame.getContentPane().add(lblExportFileName);
	}
	
	/****************************************************/
	private class ButtonListener implements ActionListener
	{

		@Override
		public void actionPerformed(ActionEvent e)
		{
			if(e.getSource() == CheckPayrollButton)
			{
				if(payrollLoadOkay())
				{
					CreateCSVButton.setEnabled(true);
					JOptionPane.showMessageDialog(null, "Database login OK, and payroll check OK..");
				}
			}//end of CheckPayrollButton event
			if(e.getSource() == CreateCSVButton)
			{
				if(createCSVFromBinary())
				{
					DoMonthEndButton.setEnabled(true);
					JOptionPane.showMessageDialog(null, "Successfully converted bin to csv and inserted into database.");
				}
			}//end of CreateCSVButton Event
			if(e.getSource() == DoMonthEndButton)
			{
				if(monthEndOkay())
				{
					JOptionPane.showMessageDialog(null, "Month End Done.");
					ExportButton.setEnabled(true);
				}
			}//end of DoMonthEndButton Event
			if(e.getSource() == ExportButton)
			{
				try {
					exportNewTransactions();
					JOptionPane.showMessageDialog(null, "Export transactions complete.");
				} catch(Exception ex) {
					ex.printStackTrace();
					JOptionPane.showMessageDialog(null, "Failed to export file");
				}
			}// end of ExportButton Event
		}
	}
	
	private void getDatabaseCredentials() {
		CredentialsInput hello = new CredentialsInput();
		
		if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null, hello, "Enter your database credentials", JOptionPane.OK_CANCEL_OPTION)) {
			username = hello.getUsername();
			password = hello.getPassword();	
		} else {
			
		}
	}
		
	private boolean payrollLoadOkay()
	{
		boolean loadOkay = false;
		try {
			getDatabaseCredentials();
			db.connect(username, password);
			
			if(!db.CheckPayrollLoad())
			{
				JOptionPane.showMessageDialog(null, "Database Locked");
			}
			else
			{
				loadOkay = true;
			}
		} catch(Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "The credentials entered were invalid or an error has occured.");
		}
		
		return loadOkay;
	}
	
	private boolean createCSVFromBinary()
	{
		boolean createCSVOkay = false;
		
		try {
			if(CsvFileTF.getText() == null || BinaryFileTF.getText() == null) {
				JOptionPane.showMessageDialog(null, "Files names invalid");
			}
			else {
				
				db.CreateCVSFromBinary(CsvFileTF.getText(), BinaryFileTF.getText());
				db.loadCSVtoDatabase(CsvFileTF.getText(),username,password);
				createCSVOkay = true;
				db.CheckPayrollUnlock();
			}
		} catch(Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "An Error occured.");
		}
		
		return createCSVOkay;
	}
	
	private boolean monthEndOkay()
	{
		boolean monthEndOkay = false;
		
		try {
			if(AliasTF.getText() == null || CtlFileTF.getText() == null) {
				JOptionPane.showMessageDialog(null, "Files names invalid");
			}
			else {
				try {
					if(db.CheckMonthEndLock())
					{
						db.PerformMonthEnd();
						db.CheckMonthEndUnLock();
						monthEndOkay = true;
					}
					else
					{
						System.out.println("Lock check failed");
					}
				} catch(Exception e) {
					e.printStackTrace();
					JOptionPane.showMessageDialog(null, "An Error occured.");
				}
				
			}
		} catch(Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "An Error occured.");
		}
		
		return monthEndOkay;
	}
	
	public void exportNewTransactions() throws Exception {
		String alias = AliasTF.getText();
		String fileName = ExportFileTF.getText();
		
		if(alias != null && fileName != null) {
			db.exportNewTransactions(fileName, alias);
		} else {
			throw new Exception();
		}
	}
}


